# 生成所有用户的 INSERT 语句并保存到文件
# 用于数据迁移
from app import create_app
from app.models import User
import os
from datetime import datetime

OUTPUT_FILE = os.path.join(os.path.dirname(__file__), 'all_users_insert.sql')

INSERT_TEMPLATE = (
    "INSERT INTO user (ip, device_uuid, device_fingerprint, signature, room_number, signature_image, created_at) "
    "VALUES ('{ip}', '{device_uuid}', '{device_fingerprint}', '{signature}', '{room_number}', '{signature_image}', '{created_at}');"
)

def escape_sql(value):
    if value is None:
        return ''
    return str(value).replace("'", "''")

def main():
    app = create_app()
    with app.app_context():
        users = User.query.all()
        with open(OUTPUT_FILE, 'w', encoding='utf-8') as f:
            for user in users:
                sql = INSERT_TEMPLATE.format(
                    ip=escape_sql(user.ip),
                    device_uuid=escape_sql(user.device_uuid),
                    device_fingerprint=escape_sql(user.device_fingerprint),
                    signature=escape_sql(user.signature),
                    room_number=escape_sql(user.room_number),
                    signature_image=escape_sql(user.signature_image),
                    created_at=user.created_at.strftime('%Y-%m-%d %H:%M:%S') if user.created_at else ''
                )
                f.write(sql + '\n')
        print(f"已生成 {len(users)} 条 INSERT 语句，保存在 {OUTPUT_FILE}")

if __name__ == "__main__":
    main()
